;
(function ($) {
    var Page = {};
    var selectNodeId = '';
    // $('input').val('')
    //树形配置
    var setting = {
        simpleData: {
            enable: true
        },
        edit: {
            enable: true,
            showRemoveBtn: true,
            showRenameBtn: false,
            editNameSelectAll: true,

        },
        view: {
            dblClickExpand: false,
            showLine: false,
            showIcon: false,
            selectedMulti: false,
            //鼠标移到元素上触发的方法
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom
        },
        data: {
            key: {
                name: "customName"
            },
            simpleData: {
                enable: true,
                idKey: "customId",
                pIdKey: "ext1",
                rootPId: 0
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                // Page.Event.getMenuShortNameList();
                selectNodeId = treeNode.customId
                $('.moduleSelect  ul').empty();/*清空木板选择*/
                $('button').attr('disabled', true);
                $('#Extra3,#Extra4,#Extra5').attr('disabled', true);
                $('#moduleName').text(''); /*清空模块名称*/
                /*判断是否满足内容在单模块文件夹内*/
                if (treeNode.getParentNode()) {
                    var dataArr = [];
                    if (!treeNode.children) {
                        if (treeNode.getPreNode() && treeNode.getPreNode().children) {
                            dataArr = [treeNode]
                        } else {
                            dataArr = treeNode.getParentNode().children
                        }
                    } else {
                        dataArr = []
                        treeNode.children.forEach(function (item, i) {/*获取文件夹下单文件*/
                            if (!item.children) {
                                dataArr.push(item)
                            }
                        })
                    }
                    dataArr.forEach(function (item, i) {
                        $('.moduleSelect  ul').append(`<li creater="${item.creater || ''}" createrTime="${item.createrTime || ''}" customId="${item.customId || ''}" parentId="${item.ext1 || ''}">${item.customName || ''}</li>`)
                    })
                    $('#add').removeAttr('disabled');
                    $('#Extra3,#Extra4,#Extra5').removeAttr('disabled');
                    $('.moduleSelect').find(`li[customId=${treeNode.customId}]`).click()
                }
                let preTree = treeNode;
                let moduleNameArr = [preTree.customName];
                let moduleName = '';
                for (var i = 1; i > 0; i++) { /*模块名称源排序*/
                    if (preTree.getParentNode()) {
                        preTree = preTree.getParentNode();
                        moduleNameArr.push(preTree.customName)
                    } else {
                        break
                    }
                }
                /*获取模块名称*/
                moduleNameArr.reverse().forEach(function (item, i) {
                    moduleName += item + '→';
                })
                $('#moduleName').text(moduleName.slice(0, moduleName.length - 1));
                $('#menuId').val(treeNode.customId);
                $('#menuName').val(treeNode.customName).removeAttr('disabled');
                $('#Extra1').val(treeNode.ext1);
                $('#Extra2').val(treeNode.ext2 || '');
                $('#Extra3').val(treeNode.ext3 || '');
                $('#Extra4').val(treeNode.ext4 || '');
                $('#Extra5').val(treeNode.ext5 || '');
                $('#save,#delete').removeAttr('disabled')
            },
            beforeRemove: function (treeId, treeNode) {
                layer.confirm("确定删除吗?",
                    {
                        btn: ["确定", "取消"],
                        title: "提示",
                        icon: 7
                    },
                    function () {
                        var lock = false;
                        var params = {
                            customId: treeNode.customId,
                            del: 1
                        }
                        updateAjax(params, 'PUT', 'deleteCoin', false, lock)
                        if (lock) return false
                    }, function () {
                        layer.closeAll();
                        $.fn.zTree.init($('#menuTree'), setting, getList());
                    });
            }
        }
    };
    Page.Event = {
        init: function () {
            // addToken();
            // this.addEvent();
            // this.getMenuTypeList();
        },
        getDictionary: function (dictType) {
            var result;
            var arg1 = {
                type: dictType,
            };
            $.ajax({
                url: "/common/getCommonDictionary",
                async: false,
                type: "GET",
                contentType: "application/json;charset=utf-8",
                data: arg1,
                success: function (res) {
                    var triageLevel = res[dictType];
                    result = triageLevel;
                }
            });
            return result;
        },
        getMenuTypeList: function () {
            var triageLevel = Page.Event.getDictionary("customTempleteType")
            var html = '';
            for (var i = 0; i < triageLevel.length; i++) {
                if (i == triageLevel.length - 1) {
                    html += "<option value='" + triageLevel[i].code + "' selected='selected'>" + triageLevel[i].value + "</option>";
                } else {
                    html += "<option value='" + triageLevel[i].code + "'>" + triageLevel[i].value + "</option>";
                }
            }
            $('#Extra3').html(html);
        },
        addEvent: function () {
            $.fn.zTree.init($('#menuTree'), setting, resultList);
            /*编辑操作*/
            $('#edit').click(function (e) {
                var id = $('#menuId').val();
                //以下的prefixKey用作redis的key，如果有shortName则优先取，否则就去取菜单编号customId，可作为唯一key
                var prefixKey = $('#Extra5').val() ? $('#Extra5').val() : id;
                window.location.href = "/template/cdStructuredCustom/customEmr?customId=" + id + "&customName=" + $('#menuName').val() + "&prefixKey=" + prefixKey;
            });
            /*新增操作*/
            $('#add').click(function () {
                $('input').not('#Extra1').val('');
                $('.moduleSelect  ul li').removeClass('moduleSelect');
                $('.moduleSelect  ul').append('<li>新模板</li>');
                $('#menuName').val('新模板').removeAttr('disabled');
            });
            /*增加医院操作*/
            $('#addRootNode').click(function () {
                var treeObj = $.fn.zTree.getZTreeObj("menuTree");
                var nodes = treeObj.getNodes();
                var lastMenuOrder;
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].isLastNode == true) {
                        lastMenuOrder = nodes[i].menuOrder;
                    }
                }
                var newNodeOrder = lastMenuOrder + 1;
                var newNode = {customId: 0, del: 0, customName: "xx医院", ext1: 0};
                var params = {
                    customId: 0,
                    customName: "xx医院",
                    del: 0,
                    ext1: 0,
                }
                var lock = false;
                updateAjax(params, 'POST', 'saveIcon', false, lock);
                if (!lock) treeObj.addNodes(null, newNode)
            })
            /*刷新操作*/
            $('#refresh').click(function () {
                $.ajax({
                    url: '/template/cdStructuredCustom/refreshRedis',
                    type: "GET",
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                        if (data.state == 200) {
                            top.layer.msg("模板缓存清除成功！");
                        } else {
                            top.layer.error("发生异常，缓存可能清除失败！");
                        }
                    }
                });
            })
            /*保存操作*/
            $('#save').click(function () {
                if ($('#menuId').val() && $('#menuId').val() != 0) {
                    var type = 'PUT'
                } else {
                    var type = 'POST'
                }
                var params = {
                    customId: $('#menuId').val(),
                    customName: $('#menuName').val(),
                    del: '0',
                    ext1: $('#Extra1').val(),
                    ext2: $('#Extra2').val(),
                    ext3: $('#Extra3').val(),
                    ext4: $('#Extra4').val(),
                    ext5: $('#Extra5').val(),
                }
                if ($('#Extra3').val()) {
                    switch ($('#Extra3').val()) {
                        case "list":
                            params.ext2 = "/customPage/list";
                            break;
                        case "edit":
                            params.ext2 = "/customPage/edit";
                            break;
                        case "list-edit":
                            params.ext2 = "/customPage/customPageIndex";
                            break;
                        case "fullScreen":
                            params.ext2 = "/customPage/fullScreen";
                            break;
                        default:
                            params.ext2 = "";
                            break;
                    }
                }
                if (params.ext5 != "") {
                    var count = judgeIfExistSameShortName(params);
                    if (count > 0) {
                        top.layer.error("已经存在相同的菜单简称，请检查是否重复后再保存！");
                        return false;
                    }
                }
                if (type == 'PUT') {
                    if (params.ext2 != "") {
                        if (params.ext5 != "") {
                            params.ext2 += "?menuShortName=" + params.ext5;
                        } else {
                            params.ext2 += "?customId=" + params.customId;
                        }
                    }
                    $.ajax({
                        url: '/template/cdStructuredCustom/justPut',
                        type: type,
                        data: JSON.stringify(params),
                        contentType: 'application/json;charset=utf-8',
                        success: function (data) {
                            if (data.state == 200) {
                                top.layer.msg("保存成功");
                                var zTree = $.fn.zTree.getZTreeObj("menuTree");
                                $.fn.zTree.init($('#menuTree'), setting, getList());
                                zTree.selectNode(zTree.getNodeByParam('customId', selectNodeId))/*选择树节点*/
                            } else {
                                top.layer.error("保存失败");
                            }
                        },
                        error: function (res) {
                            top.$(".layui-layer-btn0").css("pointer-events", "");
                            top.layer.alert("服务器连接超时!");
                            lock = true;
                        }

                    });
                } else {
                    updateAjax(params, type, 'save')
                }
            })
            /*删除操作*/
            $('#delete').click(function () {
                layer.confirm("确定删除吗?",
                    {
                        btn: ["确定", "取消"],
                        title: "提示",
                        icon: 7
                    },
                    function () {
                        var params = {
                            customId: $('#menuId').val(),
                            del: 1
                        };
                        updateAjax(params, 'PUT', 'delete')
                    });
            })
            /*点击模板操作*/
            $('body').on('click', '.moduleSelect li', function () {
                $(this).addClass('moduleSelect').siblings().removeClass('moduleSelect');
                $('button').removeAttr('disabled');
                var zTree = $.fn.zTree.getZTreeObj("menuTree");
                zTree.selectNode(zTree.getNodeByParam('customId', $(this).attr('customid')))/*选择树节点*/
                $('#menuId').val($(this).attr('customid'));
                $('#menuName').val($(this).text()).removeAttr('disabled');
                $('#Extra1').val($(this).attr('parentid'));
                // $('#createName').val($(this).attr('creater')).removeAttr('disabled');
                // $('#createTime').val($(this).attr('creatertime'));
            })

        }
    };

    function judgeIfExistSameShortName(params) {
        var count = 0;
        $.ajax({
            url: '/template/cdStructuredCustom/judgeIfExistSameShortName',
            type: 'GET',
            data: params,
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (data) {
                count = data.results.result
            }
        });
        return count;
    }

    function updateAjax(params, type, way, async, lock) {
        $.ajax({
            url: '/template/cdStructuredCustom',
            type: type,
            data: JSON.stringify(params),
            contentType: 'application/json;charset=utf-8',
            async: async || true,
            success: function (data) {
                if (data.state == 200) {
                    switch (way) {
                        case "delete":
                            top.layer.msg("删除成功！");
                            break;
                        case "deleteCoin":
                            top.layer.msg("删除成功");
                            break;
                        case "save":
                            top.layer.msg("保存成功");
                            break;
                        case "saveIcon":
                            top.layer.msg("新增成功");
                            break;
                        default:
                            break;
                    }
                    var zTree = $.fn.zTree.getZTreeObj("menuTree");
                    $.fn.zTree.init($('#menuTree'), setting, getList());
                    zTree.selectNode(zTree.getNodeByParam('customId', selectNodeId))/*选择树节点*/
                } else {
                    switch (way) {
                        case "delete":
                            top.layer.error("删除失败！", res.msg);
                            break;
                        case "delete":
                            top.layer.error("删除失败！", res.msg);
                            lock = true;/*树形删除锁*/
                            break;
                        case "save":
                            top.layer.error("保存失败");
                            break;
                        case "saveIcon":
                            top.layer.error("新增失败");
                            lock = true;/*树形新增锁*/
                            break;
                        default:
                            break;
                    }
                }
            },
            error: function (res) {
                top.$(".layui-layer-btn0").css("pointer-events", "");
                top.layer.alert("服务器连接超时!");
                lock = true;
            }

        });
        return lock
    }

    function getList() {
        var resultList;
        $.ajax({
            url: '/template/cdStructuredCustom/customEmrList/query',
            type: 'GET',
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (data) {
                if (data.state == 200 && data.results) {
                    resultList = data.results.cdStructuredCustom
                } else {
                    top.layer.alert(data.msg);
                }
            },
            error: function (res) {
                top.$(".layui-layer-btn0").css("pointer-events", "");
                top.layer.alert("服务器连接超时!");
                lock = true;
            }
        });
        return resultList
    }

    Page.Event.init();
})(jQuery);

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
};

function addHoverDom(treeId, treeNode) {
    var newCount = 1;
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);

    if (btn) btn.bind("click", function () {
        var zTree = $.fn.zTree.getZTreeObj("menuTree");
        zTree.addNodes(treeNode, {customId: (0), ext1: treeNode.customId, customName: "new node"});
        return false;
    });

    $("#" + treeNode.tId + "_remove").click(function () {
        console.log('click remove');
    });
};


/*光标移到到文本末尾*/
function moveEnd(obj) {
    obj.focus();
    var range = window.getSelection();
    range.selectAllChildren(obj)
    range.collapseToEnd()
}

